package com.huyi.system.schedule;

import java.util.List;

import javax.annotation.PostConstruct;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.huyi.system.schedule.entity.Job;
import com.huyi.system.schedule.mapper.JobMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 初始化job
 * 
 * @author shengli.hu
 *
 */
@Slf4j
@Component
public class ScheduleJobInit {

	@Autowired
	private Scheduler scheduler;

	@Autowired
	private JobMapper jobMapper;

	/**
	 * 项目启动时，初始化定时器
	 */
	@PostConstruct
	public void init() {
		List<Job> jobList = jobMapper.selectList(null);
		for (Job job : jobList) {
			CronTrigger cronTrigger = getCronTrigger(job.getJobId());
			// 如果不存在，则创建
			if (cronTrigger == null) {
				createScheduleJob(job);
			} else {
				updateScheduleJob(job);
			}
		}
	}

	/**
	 * 获取触发器key
	 */
	public static TriggerKey getTriggerKey(Long jobId) {
		return TriggerKey.triggerKey(ScheduleConstants.TASK_CLASS_NAME + jobId);
	}

	/**
	 * 获取jobKey
	 */
	public static JobKey getJobKey(Long jobId) {
		return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId);
	}

	/**
	 * 获取表达式触发器
	 */
	public CronTrigger getCronTrigger(Long jobId) {
		try {
			return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
		} catch (SchedulerException e) {
			log.error("getCronTrigger 异常：", e);
		}
		return null;
	}

	/**
	 * 创建定时任务
	 */
	public void createScheduleJob(Job job) {
		try {
			// 构建job信息
			JobDetail jobDetail = JobBuilder.newJob(ScheduleBaseJob.class).withIdentity(getJobKey(job.getJobId())).build();

			// 表达式调度构建器
			CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
			cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder);

			// 按新的cronExpression表达式构建一个新的trigger
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(job.getJobId()))
					.withSchedule(cronScheduleBuilder).build();

			// 放入参数，运行时的方法可以获取
			jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job);

			scheduler.scheduleJob(jobDetail, trigger);

			// 暂停任务
			if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) {
				pauseJob(job.getJobId());
			}
		} catch (Exception e) {
			log.error("createScheduleJob 异常：", e);
		}
	}

	/**
	 * 更新定时任务
	 */
	public void updateScheduleJob(Job job) {
		try {
			TriggerKey triggerKey = getTriggerKey(job.getJobId());

			// 表达式调度构建器
			CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
			cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder);

			CronTrigger trigger = getCronTrigger(job.getJobId());

			// 按新的cronExpression表达式重新构建trigger
			trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();

			// 参数
			trigger.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job);

			scheduler.rescheduleJob(triggerKey, trigger);

			// 暂停任务
			if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) {
				pauseJob(job.getJobId());
			}

		} catch (Exception e) {
			log.error("SchedulerException 异常：", e);
		}
	}

	/**
	 * 立即执行任务
	 */
	public int run(Job job) {
		int rows = 0;
		try {
			// 参数
			JobDataMap dataMap = new JobDataMap();
			dataMap.put(ScheduleConstants.TASK_PROPERTIES, job);

			scheduler.triggerJob(getJobKey(job.getJobId()), dataMap);
			rows = 1;
		} catch (SchedulerException e) {
			log.error("run 异常：", e);
		}
		return rows;
	}

	/**
	 * 暂停任务
	 */
	public void pauseJob(Long jobId) {
		try {
			scheduler.pauseJob(getJobKey(jobId));
		} catch (SchedulerException e) {
			log.error("pauseJob 异常：", e);
		}
	}

	/**
	 * 恢复任务
	 */
	public void resumeJob(Long jobId) {
		try {
			scheduler.resumeJob(getJobKey(jobId));
		} catch (SchedulerException e) {
			log.error("resumeJob 异常：", e);
		}
	}

	/**
	 * 删除定时任务
	 */
	public void deleteScheduleJob(Long jobId) {
		try {
			scheduler.deleteJob(getJobKey(jobId));
		} catch (SchedulerException e) {
			log.error("deleteScheduleJob 异常：", e);
		}
	}

	public static CronScheduleBuilder handleCronScheduleMisfirePolicy(Job job, CronScheduleBuilder cb)
			throws Exception {
		switch (job.getMisfirePolicy()) {
		case ScheduleConstants.MISFIRE_DEFAULT:
			return cb;
		case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
			return cb.withMisfireHandlingInstructionIgnoreMisfires();
		case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
			return cb.withMisfireHandlingInstructionFireAndProceed();
		case ScheduleConstants.MISFIRE_DO_NOTHING:
			return cb.withMisfireHandlingInstructionDoNothing();
		default:
			throw new Exception(
					"The task misfire policy '" + job.getMisfirePolicy() + "' cannot be used in cron schedule tasks");
		}
	}
}
